package com.tanhua.manage.jobs;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.manage.domain.AnalysisByDay;
import com.tanhua.manage.mapper.AnalysisByDayMapper;
import com.tanhua.manage.mapper.LogMapper;
import com.tanhua.manage.utils.ComputeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 概要统计分析定时任务类
 */
@Component
@Slf4j
public class AnalysisByDayJob {

    @Autowired
    private AnalysisByDayMapper analysisByDayMapper;

    @Autowired
    private LogMapper logMapper;

    /**
     * 基于日志表 概要统计分析数据
     * 每隔5秒执行一次任务
     */
    @Scheduled(cron = "0 0 * * * ?")
    public void AnalysisByLog(){
        log.debug("************概要统计分析定时任务开始执行*****************"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        String todayTime = DateUtil.formatDate(new Date());  //今日时间 yyyy-MM-dd
        String yesterdayTime = ComputeUtil.offsetDay(new Date(),-1);  //昨天时间yyyy-MM-dd
        //a.根据今日时间查询概要统计分析表中记录是否存在
        QueryWrapper<AnalysisByDay> queryWrapper =  new QueryWrapper<>();
        queryWrapper.eq("record_date",todayTime);
        AnalysisByDay analysisByDay = analysisByDayMapper.selectOne(queryWrapper);

        DateTime nowTime = DateUtil.parse(todayTime);
        //b.记录不存在，往表中保存记录
        if(analysisByDay == null){
            analysisByDay = new AnalysisByDay();
            analysisByDay.setRecordDate(nowTime);//今日时间
            analysisByDay.setNumRetention1d(logMapper.queryNumRetention1d(todayTime,yesterdayTime));//次日留存用户数
            analysisByDay.setNumLogin(logMapper.queryNumLoginRegistered(todayTime,"0101"));//登陆次数
            analysisByDay.setNumActive(logMapper.queryNumActive(todayTime));//活跃用户数
            analysisByDay.setNumRegistered(logMapper.queryNumLoginRegistered(todayTime,"0102"));//新注册用户数
            analysisByDay.setCreated(nowTime);
            analysisByDay.setUpdated(nowTime);
            analysisByDayMapper.insert(analysisByDay);
        }else {
            //c.记录存在，更新记录
            analysisByDay.setNumRetention1d(logMapper.queryNumRetention1d(todayTime,yesterdayTime));//次日留存用户数
            analysisByDay.setNumLogin(logMapper.queryNumLoginRegistered(todayTime,"0101"));//登陆次数
            analysisByDay.setNumActive(logMapper.queryNumActive(todayTime));//活跃用户数
            analysisByDay.setNumRegistered(logMapper.queryNumLoginRegistered(todayTime,"0102"));//新注册用户数
            analysisByDay.setUpdated(nowTime);
            analysisByDayMapper.updateById(analysisByDay);
        }
        log.debug("************概要统计分析定时任务执行结束*****************"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    }
}
